<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use fast\Random;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\Db;
use think\Lang;
use think\Response;
use think\Validate;

/**
 * Ajax异步请求接口
 * @internal
 */
class Ajax extends Backend
{

    protected $noNeedLogin = ['lang','getMobileCode'];
    protected $noNeedRight = ['*'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
    }

    /**
     * 加载语言包
     */
    public function lang()
    {
        $this->request->get(['callback' => 'define']);
        $header = ['Content-Type' => 'application/javascript'];
        if (!config('app_debug')) {
            $offset = 30 * 60 * 60 * 24; // 缓存一个月
            $header['Cache-Control'] = 'public';
            $header['Pragma'] = 'cache';
            $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        }

        $controllername = input("controllername");
        //默认只加载了控制器对应的语言名，你还根据控制器名来加载额外的语言包
        $this->loadlang($controllername);
        return jsonp(Lang::get(), 200, $header, ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');

        //必须还原upload配置,否则分片及cdnurl函数计算错误
        Config::load(APP_PATH . 'extra/upload.php', 'upload');

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }

    /**
     * 通用排序
     */
    public function weigh()
    {
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        if (!Validate::is($table, "alphaDash")) {
            $this->error();
        }
        //主键
        $pk = $this->request->post("pk");
        //排序的方式
        $orderway = strtolower($this->request->post("orderway", ""));
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = $pk && preg_match("/^[a-z0-9\-_]+$/i", $pk) ? $pk : (Db::name($table)->getPk() ?: 'id');
        $pid = $this->request->post("pid", "");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v[$prikey];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, $ids);
        $desc_id = isset($sour[$position]) ? $sour[$position] : end($sour);    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc($ids, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            if (!isset($weighdata[$offset])) {
                continue;
            }
            $weighids[$n] = $weighdata[$offset];
            Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
        }
        $this->success();
    }

    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
        try {
            $type = $this->request->request("type");
            switch ($type) {
                case 'all':
                    // no break
                case 'content':
                    //内容缓存
                    rmdirs(CACHE_PATH, false);
                    Cache::clear();
                    if ($type == 'content') {
                        break;
                    }
                case 'template':
                    // 模板缓存
                    rmdirs(TEMP_PATH, false);
                    if ($type == 'template') {
                        break;
                    }
                case 'addons':
                    // 插件缓存
                    Service::refresh();
                    if ($type == 'addons') {
                        break;
                    }
                case 'browser':
                    // 浏览器缓存
                    // 只有生产环境下才修改
                    if (!config('app_debug')) {
                        $version = config('site.version');
                        $newversion = preg_replace_callback("/(.*)\.([0-9]+)\$/", function ($match) {
                            return $match[1] . '.' . ($match[2] + 1);
                        }, $version);
                        if ($newversion && $newversion != $version) {
                            Db::startTrans();
                            try {
                                \app\common\model\Config::where('name', 'version')->update(['value' => $newversion]);
                                \app\common\model\Config::refreshFile();
                                Db::commit();
                            } catch (\Exception $e) {
                                Db::rollback();
                                exception($e->getMessage());
                            }
                        }
                    }
                    if ($type == 'browser') {
                        break;
                    }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        \think\Hook::listen("wipecache_after");
        $this->success();
    }

    /**
     * 读取分类数据,联动列表
     */
    public function category()
    {
        $type = $this->request->get('type', '');
        $pid = $this->request->get('pid', '');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($pid || $pid === '0') {
            $where['pid'] = $pid;
        }
        if ($type) {
            $where['type'] = $type;
        }

        $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();

        $this->success('', '', $categorylist);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        $params = $this->request->get("row/a");
        if (!empty($params)) {
            $province = isset($params['province']) ? $params['province'] : null;
            $city = isset($params['city']) ? $params['city'] : null;
        } else {
            $province = $this->request->get('province');
            $city = $this->request->get('city');
        }
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== null) {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city !== null) {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }
        $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
        $this->success('', '', $provincelist);
    }

    /**
     * 读取省市区数据,联动列表(同一个表单多个省市区参数问题)
     */
    public function area1()
    {
        $params = $this->request->get("row/a");
        if (!empty($params)) {
            $province = isset($params['bank_province']) ? $params['bank_province'] : null;
            $city = isset($params['bank_area']) ? $params['bank_area'] : null;
        } else {
            $province = $this->request->get('bank_province');
            $city = $this->request->get('bank_area');
        }
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== null) {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city !== null) {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }
        $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
        $this->success('', '', $provincelist);
    }

    /**
     * 读取省市区数据,联动列表(同一个表单多个省市区参数问题)
     */
    public function area2()
    {
        $params = $this->request->get("row/a");
    
        if (!empty($params)) {
            $province = isset($params['province_s']) ? $params['province_s'] : null;
            $city = isset($params['city_s']) ? $params['city_s'] : null;
            
        } else {
            $province = $this->request->get('province_s');
            $city = $this->request->get('city_s');
        }
        //var_dump($province);die;
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
       
        if ($province !== null) {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city !== null) {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }
        
        $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
        $this->success('', '', $provincelist);
    }

    /**
     * 生成后缀图标
     */
    public function icon()
    {
        $suffix = $this->request->request("suffix");
        $suffix = $suffix ? $suffix : "FILE";
        $data = build_suffix_image($suffix);
        $header = ['Content-Type' => 'image/svg+xml'];
        $offset = 30 * 60 * 60 * 24; // 缓存一个月
        $header['Cache-Control'] = 'public';
        $header['Pragma'] = 'cache';
        $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        $response = Response::create($data, '', 200, $header);
        return $response;
    }

    //获取角色信息
    public function getRule()
    {
        $group = [
            [
                'value'=>0,
                'name'=>'无推广人'
            ],
            [
                'value'=>1,
                'name'=>'中心'
            ],
            [
                'value'=>2,
                'name'=>'空间'
            ],
            [
                'value'=>3,
                'name'=>'合伙人'
            ]
        ];
        $this->success('', '', $group);
    }
    public function getpat()
    {
        $group = [
            [
                'value'=>3,
                'name'=>'合伙人'
            ]
        ];
        $this->success('', '', $group);
    }

    //获取空间和中心信息
    public function getStore()
    {
        $type = $this->request->param();
       // var_dump($type['row']['first']);die;
        $type = $type['row']['first'] ? $type['row']['first'] : 0;
        if (empty($type)) {
            $this->success('', '', []);
        }

        if (in_array($type,[1,2])) {
            $store = db('store')->field('id as value,store_name as name')->where('type',$type)->where(['is_del'=>0,'is_ban'=>0])->select();
        } else {
            $store = db('user')->field('id as value,username as name')->where(['is_jin'=>0,'type'=>3])->select();
        }
        $this->success('', '', $store);
    }

    public function getPartner()
    {
        $type = $this->request->param();
        // var_dump($type);die;
       // var_dump($type['row']['first']);die;
        
        $where=[];
        if(isset($type['id']))
        {
            // var_dump(11);
            $where['id']=['neq',$type['id']];
        }
        if(isset($type['store_id']))
        {
            $where['store_id']=$type['store_id'];
        }
        else
        {
            $admininfo=$this->auth->getUserInfo();
            if($admininfo['store_id'])
            {
                $where['store_id']=$admininfo['store_id'];
            }
            
        }
        // var_dump($where);
        // var_dump($type['row']['first']);
        $type = isset($type['row']['first']) ? $type['row']['first'] : 0;
        
        if (empty($type)) {
            $this->success('', '', []);
        }
        if (in_array($type,[1,2])) {
            $store = db('store')->field('id as value,store_name as name')->where('type',$type)->where(['is_del'=>0,'is_ban'=>0])->select();
        } else {
            

            $store = db('user')->field('id as value,username as name')->where('is_jin',0)->where($where)->where('type','3')->select();
        }
        $this->success('', '', $store);
    }

    //selectpage插件获取中心/空间可展示产品
    public function getAllgoods()
    {
        $where = [];
        $nickName = $this->request->param("goods_name");
        if (!empty($nickName)) {
            $where = "goods_name LIKE '%".$nickName."%'";
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");
        $storeId = $this->request->param("store_id");

        $store = db('store')->where('id',$storeId)->find();
        $notGoods = $store['not_goods'] ? explode(',',$store['not_goods']) : [];

        $goods = db('goods')
            ->field('id,goods_name')
            ->where($where)
            ->where('id','not in',$notGoods)
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('goods')
            ->field('id,goods_name')
            ->where($where)
            ->where('id','not in',$notGoods)
            ->count();
        return json(['list'=>$goods,'total'=>$count]);
    }

    //selectpage获取所有组装区域
    public function getAllregion()
    {
        if($this->request->request("keyValue")){

            $ids = $this->request->request("keyValue");
            $region = db('area')
                ->field('id,mergename as name')
                ->where('id','in',$ids)
//                ->page($pageNumber,$pageSize)
                ->select();

            $count = db('area')
                ->field('id,mergename as name')
                ->where('id','in',$ids)
//                ->page($pageNumber,$pageSize)
                ->count();
            return json(['list'=>$region,'total'=>$count]);
        }

        $where = [];
        $nickName = $this->request->param("name");
        if (!empty($nickName)) {
            $where = "mergename LIKE '%".$nickName."%'";
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $region = db('area')
            ->field('id,mergename as name')
            ->where($where)
            ->where(['level'=>3])
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('area')
            ->field('id,mergename as name')
            ->where($where)
            ->where(['level'=>3])
            ->count();
        return json(['list'=>$region,'total'=>$count]);
    }
    public function getAllsalesman()
    {
        $where = [];
        $salesman_id = $this->request->param("salesman_id");
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $where['is_del']='0';
        $where['id']=['neq',$salesman_id];
        $goods = db('salesman')
            ->field('id,name')
            ->where($where)
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('salesman')
            ->where($where)
            ->count();
        return json(['list'=>$goods,'total'=>$count]);
    }


    //selectpage获取所有中心/空间
    public function getAllstore()
    {
        $storeName = $this->request->param("name");
        $type = $this->request->param("type");
        $where = [];

        if (!empty($type)) {
            $where['type'] = $type;
        }
        if (!empty($storeName)) {
            $where['store_name'] = ['like',"%$storeName%"];
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $store = db('store')
            ->field('id,store_name as name')
            ->where($where)
            ->where(['is_ban'=>0,'is_del'=>0])
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('store')
            ->field('id,store_name as name')
            ->where($where)
            ->where(['is_ban'=>0,'is_del'=>0])
            ->count();
        return json(['list'=>$store,'total'=>$count]);
    }


    //selectpage获取所有商品标签
    public function getAlltag()
    {

        if($this->request->request("keyValue")){
            $id = $this->request->request('keyValue');
            $kuaiDi = db('goodstag')->field('tag_name as name,id')->where('id',$id)->find();
            return json([
                'total'=>1,
                'list'=>[$kuaiDi]
            ]);die;
        }

        $storeName = $this->request->param("name");
        $where = "";
        if (!empty($storeName)) {
            $where .= " tag_name LIKE '%".$storeName."%'";
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $store = db('goodstag')
            ->field('id,tag_name as name')
            ->where($where)
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('goodstag')
            ->field('id,tag_name as name')
            ->where($where)
            ->count();
        return json(['list'=>$store,'total'=>$count]);
    }

    //selectpage获取所有合伙人 $storeId空间/中心ID
    public function getAllusers()
    {
        $where = [];
        $userName = $this->request->param("name");
        if (!empty($userName)) {
            $where = "username LIKE '%".$userName."%'";
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $user = db('user')
            ->field('id,username as name')
            ->where($where)
            ->where(['is_jin'=>0,'type'=>3])
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('user')
            ->field('id,username as name')
            ->where($where)
            ->where(['is_jin'=>0,'type'=>3])
            ->count();
        return json(['list'=>$user,'total'=>$count]);
    }

    //selectpage获取指定中心/空间合伙人
    public function getStoreuser()
    {
        $where = [];
        $userName = $this->request->param("name");
        $storeId = $this->auth->store_id;
        if (!empty($userName)) {
            $where = "username LIKE '%".$userName."%'";
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $user = db('user')
            ->field('id,username as name')
            ->where($where)
            ->where('store_id',$storeId)
            ->where(['is_jin'=>0,'type'=>3])
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('user')
            ->field('id,username as name')
            ->where($where)
            ->where('store_id',$storeId)
            ->where(['is_jin'=>0,'type'=>3])
            ->count();
        return json(['list'=>$user,'total'=>$count]);
    }

    //获取快递公司
    public function getKuaiDi()
    {
        if($this->request->request("keyValue")){
            $code = $this->request->request('keyValue');
            $kuaiDi = db('express_code')->field('title as name,id as code')->where('code',$code)->find();
            return json([
                'total'=>1,
                'list'=>[$kuaiDi]
            ]);
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");
        $kuaiDi = db('express_code')->field('title as name,id as code')->page($pageNumber,$pageSize)->select();
        $count = db('express_code')->count();
        return json(['list'=>$kuaiDi,'total'=>$count]);
    }

    //selectpage获取所有业务员
    public function getAllYewu()
    {
        if($this->request->request("keyValue")){
            $ids = $this->request->request("keyValue");
            $saleman = db('salesman')
                ->field('id,name')
                ->where('id','in',$ids)
//                ->page($pageNumber,$pageSize)
                ->select();

            $count = db('salesman')
                ->field('id,name')
                ->where('id','in',$ids)
//                ->page($pageNumber,$pageSize)
                ->count();
            return json(['list'=>$saleman,'total'=>$count]);
        }

        $where = [];
        $nickName = $this->request->param("name");
        if (!empty($nickName)) {
            $where = "name LIKE '%".$nickName."%'";
        }
        $pageNumber = $this->request->param("pageNumber");
        $pageSize = $this->request->param("pageSize");

        $saleman = db('salesman')
            ->field('id,name')
            ->where($where)
            ->page($pageNumber,$pageSize)
            ->select();

        $count = db('salesman')
            ->field('id,name')
            ->where($where)
            ->count();
        return json(['list'=>$saleman,'total'=>$count]);
    }

    //检测区域下是否有中心
    public function checkCenter()
    {
        $area = $this->request->param('area');
        $store = db('store')->where('find_in_set('.$area.',area_ids)')->where(['type'=>1,'is_ban'=>0,'is_del'=>0,'xvstatus'=>2])->find();
        if (empty($store)) {
            return json([
                'code'=>201,
                'msg'=>'该区域下无中心'
            ]);
        } else{
            return json([
                'code'=>200,
                'msg'=>'该区域下有中心'
            ]);
        }
    }

    //空间中心采购实时计算采购单价格
    public function jiSuanCaiGou()
    {
        $storeId = $this->request->param('store_id');
        if (empty($storeId)) {
            $storeId = $this->auth->store_id;
        }
        $store = db('store')->where('id',$storeId)->find();
        if (empty($_POST['setGoods']) || empty($_POST['setNum'])){
            $back = [
                'orderPrice'=>"0",
                'isFirst'=>"首购"
            ];
            return json($back);
        }

        $setGoods = explode(',',$_POST['setGoods']);
        $setNum = explode(',',$_POST['setNum']);
        if (empty($setGoods) || empty($setNum)) {
            $this->error('请选择采购商品再提交');
        }

        $orderTotalPrice = 0;
        $isFirst = isFirst($setGoods,$setNum,$store['type'],$store['first_storage_balance']);//1首购  2复购
        foreach ($setGoods AS $key => $value) {
            $goodsPay = getCaiPrice($value,$store['type'],$isFirst);//采购价
            $orderTotalPrice+=$goodsPay*$setNum[$key];//订单实付价
        }
        //var_dump($orderTotalPrice);die;
        //$ratio = getGoodsCaiRatio($goods,$store['type'],$isFirst);//采购比例

        $back = [
            'orderPrice'=>(string)$orderTotalPrice,
            'isFirst'=>$isFirst == 1 ? '首购' : '复购'
        ];
        return json($back);
    }

    //合伙人采购实时计算采购单价格
    public function jiSuanCaiGouH()
    {
        $userId = $this->request->param('user_id');
        if (empty($userId)) {
            return json([
                'code'=>201,
                'msg'=>'未知合伙人'
            ]);
        }
        $user = db('user')->where('id',$userId)->find();
        if (empty($_POST['setGoods']) || empty($_POST['setNum'])){
            $back = [
                'orderPrice'=>"0",
                'isFirst'=>"首购"
            ];
            return json($back);
        }
        $setGoods = explode(',',$_POST['setGoods']);
        $setNum = explode(',',$_POST['setNum']);

        if (empty($setGoods) || empty($setNum)) {
            $this->error('请选择采购商品再提交');
        }

        $orderTotalPrice = 0;
        $isFirst = isFirst($setGoods,$setNum,3,$user['first_storage_balance']);//1首购  2复购
        foreach ($setGoods AS $key => $value) {
            $goodsPay = getCaiPrice($value,3,$isFirst);//采购价
            $orderTotalPrice+=$goodsPay*$setNum[$key];//订单实付价
        }
        $orderTotalPrice = (string)$orderTotalPrice;
        //var_dump($orderTotalPrice);die;
        //$ratio = getGoodsCaiRatio($goods,$store['type'],$isFirst);//采购比例
        if ($isFirst == 2) {
            //复购判断复购首购金额
            $priceRule = db('config')->where(['name'=>'part_fugou_first_price','group'=>'basic'])->value('value');
            if ($priceRule < $user['first_storage_balance']) {
                $this->error('请将首购剩余金额花费到￥'.$priceRule."以下，才能使用复购比例");
            }
        }
        $back = [
            'code'=>1,
            'orderPrice'=>$orderTotalPrice,
            'isFirst'=>$isFirst == 1 ? '首购' : '复购'
        ];
        return json($back);
    }

    //获取手机验证码
    public function getMobileCode()
    {
        $mobile = $this->request->post('mobile',0);
        $username = $this->request->post('username',0);
        $type = $this->request->post('type',0);
        if($type==1)
        {
            $adminInfo = db('admin')->where(['mobile'=>$mobile,'username'=>$username,'store_id'=>0])->find();
        }
        if($type==2)
        {
            $adminInfo = db('admin')->where(['mobile'=>$mobile,'username'=>$username,'store_id'=>['neq',0]])->find();
        }

        $time = time();
        
        if (empty($adminInfo)) {
            $back = [
                'code' => 201,
                'msg' => '用户与手机号不匹配'
            ];
            return json($back);
        }

        $codes = db('login_codes')->where(['admin_id'=>$adminInfo['id'],'status'=>0])->order('addtime DESC')->find();
        if (!empty($codes)) {
            $jianGe = $time-$codes['addtime'];
            if ($jianGe <= 60) {
                $back = [
                    'code' => 201,
                    'msg' => '请勿频繁发送验证码'
                ];
                return json($back);
            }
        }
        //调用发送手机验证码
        $mobileCode = 1234;//duanxin($mobile);
        if (empty($mobileCode)) {
            $back = [
                'code' => 201,
                'msg' => '短信错误'
            ];
            return json($back);
        }
        //记录验证码
        db('login_codes')->insert([
            'mobile'=>$mobile,
            'admin_id'=>$adminInfo['id'],
            'code'=>$mobileCode,
            'expire_time'=>$time+900,
            'addtime'=>time(),
            'status'=>0
        ]);
        $back = [
            'code' => 200,
            'msg' => '发送成功'
        ];
        return json($back);
    }

    public function getStorePrice()
    {
        $storeId = $this->request->param('store_id');
        $storeId = $storeId ? $storeId : $this->auth->store_id;
        $store = db('store')->where('id',$storeId)->find();
        $backN = '余额：￥'.$store['storage_balance'];
        if ($this->roleType == 'zongbu') {
            $backN = $store['store_name'].'，余额：￥'.$store['storage_balance'];
        }
        return json([
            'code' => 200,
            'priceHtml' => $backN
        ]);
    }

    public function getUserPrice()
    {
        $uid = $this->request->param('u_id');
        $user = db('user')->where('id',$uid)->find();
        $backN = $user['username'].'，余额：￥'.$user['storage_balance']."，首购剩余金额：￥".$user['first_storage_balance'];
        return json([
            'code' => 200,
            'priceHtml' => $backN
        ]);
    }

    //根据中心/空间ID获取收货地址
    public function getStoreAddress()
    {
        $storeId = $this->request->param('store_id');
        $store = db('store')->where('id',$storeId)->find();
        return json([
            'code' => 200,
            'row' => [
                'province_s'=>$store['province_s'],
                'city_s'=>$store['city_s'],
                'area_s'=>$store['area_s'],
                'address_s'=>$store['address_s'],
                'name_s'=>$store['name_s'],
                'tel_s'=>$store['tel_s'],
            ]
        ]);
    }

    //根据用户ID获取地址姓名和电话
    public function getUserAddress()
    {
        $uid = $this->request->param('uid');
        $user = db('address')->where('user_id',$uid)->where('is_default',1)->find();
        return json([
            'code' => 200,
            'row' => [
                'username'=>$user['name'],
                'tel'=>$user['tel']
            ]
        ]);
    }

}
